<?php
// 用户获取指定优惠券
require_once $this->website['path']['action'] . '/app/token.php';
$json = array('status' => 'error', 'msg' => '', 'data' => '');

$id = fn_post('id');

$coupon = $this->website['class']['db']
	->table('coupon')
	->where('id=?', $id)
	->one();

if (!$id || !is_numeric($id)) {
	$json['msg'] = '领取失败,非法优惠券';
} elseif (!($coupon['id'] ?? false)) {
	$json['msg'] = '领取失败,未找到优惠券';
} elseif ($coupon['endtime'] < $_SERVER['REQUEST_TIME']) {
	$json['msg'] = '领取失败,优惠券已过期';
} elseif ($coupon['num'] > 0 && $coupon['used'] > 0 && $coupon['num'] >= $coupon['used']) {
	$json['msg'] = '领取失败,优惠券已领完';
	$json['data'] = $coupon;
} else if ($this->website['class']['db']
	->table('coupon_user')
	->where('cid=? and uid=?', $id, $basic['uid'])
	->limit(1)
	->count()) {
	$json['msg'] = '领取失败,已领用过';
} else {

	if (preg_match("/^\d+$/", $coupon['tm'])) {
//领取后XX天内有效
		$endtime = $_SERVER['REQUEST_TIME'] + $coupon['tm'];
	} else {
		$endtime = $coupon['tm'];
	}
	$coupon_user_id = $this->website['class']['db']
		->table('coupon_user')
		->field('cid', 'uid', 'endtime', 'createtime')
		->value($id, $basic['uid'], $endtime, $_SERVER['REQUEST_TIME'])
		->insert();
	$this->website['class']['db']
		->table('coupon')
		->field('used')
		->value(1)
		->where('id=?', $id)
		->increase();
	if ($coupon_user_id) {
		$json['status'] = 'ok';
		$json['msg'] = '领取成功!';
	} else {
		$json['msg'] = '领取失败';
	}
}
// $json['sql'] = $this->website['class']['db']->sql;

$this->json_encode_encrypt($json);